var gulp = require('gulp'),
	concat = require('gulp-concat'),
	minifyCss = require('gulp-minify-css'),
	uglify = require('gulp-uglify'),
	notify = require('gulp-notify'),
	plumber = require('gulp-plumber'),
	htmlreplace = require('gulp-html-replace'),
	rev = require('gulp-rev-append'),
	crypto = require('path');
	
var browserSync = require('browser-sync').create();

//压缩合并css
gulp.task('wbcBuildCss' , function(){
	gulp.src('src/**/*.css')
		.pipe(plumber({errorHandler:notify.onError('Error: <%= error.message %>')}))
		.pipe(concat('build.css'))
		.pipe(minifyCss())
		.pipe(gulp.dest('dist/css'));
});

//压缩/合并js
gulp.task('wbcBuildJs', function(){
	gulp.src(['src/js/index1.js','src/index2.js'])
		.pipe(plumber({errorHandler:notify.onError('Error: <%= error.message %>')}))
		.pipe(concat('build.js'))
		.pipe(uglify())
		.pipe(gulp.dest('dist/js'));
})

//自动化构建
gulp.task('autoBuild' , function(){
	gulp.watch('src/**/*.js',['wbcBuildJs']);
	gulp.watch('src/**/*.css',['wbcBuildCss']);
	gulp.watch('index.html',['wbcBuildCss']);
})

//替换HTML页面中的css，js路径
gulp.task('wbcBuildHtml',function(){
	var hash = crypto.vreateHash('md5');
//	var r = hash.digest('hex');
	var r = new Date().getTime();
	gulp.src('src/index.html')
		.pipe(htmlreplace({
			'gulpCss':'css/build.css?rev='+r,
			'gulpJs':'js/build.js?rev='+r
		}))
		.pipe(rev())
		.pipe(gulp.dest('dist/'));
})



////添加版本号，清除缓存
//gulp.task('wbcRev' , function(){
//	gulp.src('src/index.html')
//		.pipe(rev())
//		.pipe(gulp.dest('dist/'));
//});

//浏览器自动同步
gulp.task('bsync', function() {
    browserSync.init({
        server: {
            baseDir: "./src"
        }
    });
    gulp.watch("src/*.html").on('change', browserSync.reload);
    
});

